import {createStore} from 'redux';

let cartList = [];
if(localStorage.getItem('cartList')){
	cartList = JSON.parse(localStorage.getItem('cartList'));
}

const initState = {
	shopList: [],
	cartList
}

function reducer(state = initState, action) {
	let newState = Object.assign({}, state);
	switch (action.type) {
		case 'SET_SHOP_LIST':
			newState.shopList = action.data;
			newState = sycncData(newState);
			return newState;
		case 'ADD_CART':
			var cartList = [...newState.cartList, action.shopItem];
			newState.cartList = cartList;
			return newState;
		case 'ADD_COUNT':
			var cartList = [...newState.cartList];
			cartList.find(item=>item.id===action.id).count++;
			newState.cartList = cartList;
			newState = sycncData(newState);
			return newState;
		case 'REDUCE_COUNT':
			var cartList = [...newState.cartList];
			cartList.find(item=>item.id===action.id).count--;
			newState.cartList = cartList;
			newState = sycncData(newState);
			return newState;
		case 'REMOVE_ITEM':
			var cartList = [...newState.cartList];
			var item = cartList.find(item=>item.id===action.id);
			let index = cartList.findIndex(item=>item.id===action.id);
			item.count = 1;
			cartList.splice(index, 1);
			newState.cartList = cartList;
			newState = sycncData(newState);
			return newState;
		case 'CLEAR_CART':
			var shopList = [...newState.shopList];
			for(let item of shopList) {
				item.count = 1;
			}
			newState.cartList = [];
			return newState;
		default:
			return newState;
	}
}

function sycncData(state) {
	let cartList = [...state.cartList];
	let shopList = [...state.shopList];
	for(let item of cartList) {
		let shopItem = shopList.find(value=>value.id===item.id);
		shopItem.count = item.count;
	}
	state = {
		cartList,
		shopList
	}
	return state;
}

const store = createStore(reducer);

export default store;